package com.ssr.master.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;

import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.support.http.StatViewServlet;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangPeng
 * @Describe //todo
 * @date
 * @updateBy
 * @other
 **/

public class DruidConfig {

    /**
     *
     * 绑定配置文件中的参数
     *
     * @Describe //todo
     * @author ZhangPeng
     * @date 2020/6/12 0:13
     * @
     * @param
     * @return javax.sql.DataSource
     * @other
    **/
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean(destroyMethod = "close", initMethod = "init")
    public DataSource druid(){
        //自定义数据源为DruidDataSource
        return  new DruidDataSource();
    }

    // 配置Druid的监控
    // 1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initParams = new HashMap<String,String>();
        //用户名和密码
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");
        //默认允许所有访问
        initParams.put("allow", "");
        //拒绝访问的ip
        initParams.put("deny", "10.18.172.124");

        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     *
     * 2、配置一个web监控的filter
     *
     * @Describe //todo
     * @author ZhangPeng
     * @date 2020/6/12 0:14
     * @
     * @param
     * @return org.springframework.boot.web.servlet.FilterRegistrationBean
     * @other
    **/
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParams = new HashMap<String, String>();
        initParams.put("exclusions", "*.js,*.css,*.png,*.jpg,*.ftl,*.html,*.ico,/druid/*");

        bean.setInitParameters(initParams);
        //web监控拦截所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}
